import os
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed

# 下载基础路径配置
BASE_URL = "http://61.184.202.83/rom/"
ROM_TYPES = {
    "fc":   (7000000, 7009999),
    "sfc":  (3000000, 3009999),
    "gba":  (1100000, 1109999),
    "gbc":  (6100000, 6109999),
}

# 保存路径前缀
SAVE_ROOT = "downloads"
ROM_TYPE_WORKERS = 10           # 每种类型的并发线程数
MAX_TYPE_CONCURRENCY = 4        # 同时并发几种类型

def download_rom(rom_type, rom_id):
    rom_filename = f"{rom_id:07d}.zip"
    rom_url = f"{BASE_URL}{rom_type}/{rom_filename}"
    save_dir = os.path.join(SAVE_ROOT, rom_type)
    os.makedirs(save_dir, exist_ok=True)
    local_path = os.path.join(save_dir, rom_filename)

    try:
        response = requests.get(rom_url, stream=True, timeout=10)
        response.raise_for_status()

        with open(local_path, 'wb') as file:
            for chunk in response.iter_content(chunk_size=8192):
                file.write(chunk)

        print(f"[{rom_type.upper()}] Downloaded {rom_filename}")
        return rom_filename
    except requests.exceptions.RequestException as e:
        # print(f"[{rom_type.upper()}] Failed to download {rom_filename}: {e}")
        return None

def download_rom_type(rom_type, start_id, end_id):
    print(f"Starting download for {rom_type.upper()} from {start_id} to {end_id}")
    with ThreadPoolExecutor(max_workers=ROM_TYPE_WORKERS) as executor:
        futures = [
            executor.submit(download_rom, rom_type, rom_id)
            for rom_id in range(start_id, end_id + 1)
        ]
        for future in as_completed(futures):
            _ = future.result()

def download_all_roms():
    with ThreadPoolExecutor(max_workers=MAX_TYPE_CONCURRENCY) as executor:
        futures = [
            executor.submit(download_rom_type, rom_type, start_id, end_id)
            for rom_type, (start_id, end_id) in ROM_TYPES.items()
        ]
        for future in as_completed(futures):
            _ = future.result()

if __name__ == "__main__":
    download_all_roms()
